<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\exception\ErrorException;
use think\Log;
use app\index\model\Goods as GoodsModel;
use think\Request;

class AjaxRequest extends Controller
{
    /**
     * taobao.tbk.sc.material.optional( 通用物料搜索API )
     * 淘宝客-工具-超级搜索（需要）
     * @param $ks  查找关键字
     * @param $pageSize 页数
     * @param $pageNo   分页
     * @param $sort 排序
     * @return array
     */
    public function superSearch($ks, $pageSize, $pageNo, $sort)
    {

        vendor('taobao.TopClient');
        vendor('taobao.ResultSet');
        vendor('taobao.RequestCheckUtil');
        vendor('taobao.TopLogger');
        vendor('taobao.request.TbkScMaterialOptionalRequest');

        try {
            $c = new \TopClient();
            $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
            $c->secretKey = config('web.WEB_TBSECREC');//淘宝SECREC
            $sessionKey = config('web.WEB_SESSIONKEY');//secretKey
            $req = new \TbkScMaterialOptionalRequest;
            $req->setAdzoneId(get_adzoneid(config('web.WEB_YHQPID')));//高拥PID  获取adzoneid
            $req->setSiteId(get_siteid(config('web.WEB_YHQPID')));//高拥PID  获取siteid
            $req->setQ($ks);
            $req->setSort($sort);
            $req->setPageSize($pageSize);
            $req->setPageNo($pageNo);
            $resp = $c->execute($req, $sessionKey);
            $resp = object_to_array($resp);
            $map_data = $resp['result_list']['map_data'];

            $data = array();
            $item = array();
            foreach ($map_data as $mapKey => $mapVal) {
                $item[$mapKey]['title'] = $mapVal['title'];//产品标题
                $item[$mapKey]['cid'] = 14;//通过搜索的产品都归属到这个分类中
                $item[$mapKey]['pic'] = str_replace('https', 'http', $mapVal['pict_url']);//产品主图
                $item[$mapKey]['numIid'] = $mapVal['item_id'];//产品ID
                $item[$mapKey]['couponTotalcount'] = $mapVal['coupon_total_count'];//优惠券总量
                $item[$mapKey]['couponRemaincount'] = $mapVal['coupon_remain_count'];//优惠券剩余量
                $item[$mapKey]['couponAmount'] = get_word($mapVal['coupon_info'], '减', '元');//优惠券面额
                $item[$mapKey]['price'] = $mapVal['reserve_price'];//产品一口价格
                $item[$mapKey]['couponPrice'] = $mapVal['zk_final_price'];//产品折扣价格
                $item[$mapKey]['couponRate'] = $mapVal['zk_final_price'] - $item[$mapKey]['couponAmount'];//产品劵后价=产品折扣价格-优惠券面额
                $item[$mapKey]['volume'] = $mapVal['volume'];//30天销量
                $item[$mapKey]['nick'] = $mapVal['shop_title'];//店铺名称
                $item[$mapKey]['sellerId'] = $mapVal['seller_id'];//卖家id
                $item[$mapKey]['clickUrl'] = isset($mapVal['coupon_share_url']) ? "https:" . $mapVal['coupon_share_url'] : "https:" . $mapVal['url'];// coupon_share_url:券二合一页面链接  url:推广链接
                $item[$mapKey]['commissionRate'] = $mapVal['commission_rate'] / 100;//佣金比率 1550表示15.5%
                $item[$mapKey]['commission'] = round($item[$mapKey]['couponRate'] * ($item[$mapKey]['commissionRate']), 1) / 100;//总佣金=产品劵后价*佣金比率/100
                $item[$mapKey]['commissionUser'] = round($item[$mapKey]['commission'] * 80 / 100, 1);//用户所得佣金
                $item[$mapKey]['userType'] = "0";//卖家类型  0淘宝
                $item[$mapKey]['description'] = $item[$mapKey]['title'] . '，现价只需要' . $mapVal['zk_final_price'] . '元，领券后下单还可优惠' . $item[$mapKey]['couponAmount'] . '元，赶紧抢购吧！';//描述
                $item[$mapKey]['keywords'] = implode(',', get_tags($item[$mapKey]['title']));//关键词
                $item[$mapKey]['couponStartTime'] = empty(strtotime($mapVal['coupon_start_time'])) ? time() : strtotime($mapVal['coupon_start_time']);//优惠券开始时间
                $item[$mapKey]['couponEndTime'] = empty(strtotime($mapVal['coupon_end_time'])) ? time() + (60 * 60 * 48) : strtotime($mapVal['coupon_end_time']);//优惠券结束时间
                $item[$mapKey]['addTime'] = time();//添加时间
            }

            $total_results = $resp['total_results'];//搜索到符合条件的结果总数
            $data['item_list'] = $item;
            $data['total_results'] = $total_results;//总数
            $data['current_page'] = $pageNo;//当前页
            $data['list_rows'] = $pageSize;//当前页数
            $total_page_size = $total_results / $pageSize;
            $data['total_page_size'] = $total_page_size <= 0 ? 0 : ceil($total_page_size);//总页数
        } catch (ErrorException $e) {
            Log::write('采集产品数据异常、错误：' . $e->getMessage(), 'error');
            return false;
        }
        // 保存产品数据本地库
        $this->saveGoodsItem($data['item_list']);
        return $data;
    }

    /**
     * 保存淘宝搜索出来产品数据保存到本地库（需要）
     * @param $list_item
     */
    public function saveGoodsItem($list_item)
    {

        $goodsModel = new GoodsModel();
        $data_true = array();
        foreach ($list_item as $itemKey => $itemVal) {

            // 产品的折扣价要大于 1 元的
            if ($itemVal['couponPrice'] >= 1) {
                // 查找当前产品ID本地是否存在
                $goods_id = $goodsModel->where('numIid', $itemVal['numIid'])->value('id');
                // 不存在则保存到本地
                if (empty($goods_id)) {
                    $userId = session('userid');//当前登陆用户ID
                    $itemVal['uid'] = empty($userId) ? 1 : $userId;
                    array_push($data_true, $itemVal);
                }
            }
        }

        if (!empty($data_true)) {
            try {
                $goodsModel->insertAll($data_true);
                Log::write('批量添加淘宝搜索商品成功！', 'info');
            } catch (ErrorException $e) {
                Log::write('批量添加淘宝搜索商品失败！错误信息：' . $e->getMessage(), 'error');
            }
        }
    }

    /**
     * 生成淘宝口令（需要）
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taoToken(Request $request)
    {
        if ($request->isPost()) {
            $goodsId = (int)input('goodsId');

            if (empty($goodsId)) {
                Log::write('缺少参数、产品ID不能为空', 'info');
                return json(['code' => 0, 'msg' => '产品ID不能为空', 'data' => []]);
            }

            $goodsModel = new GoodsModel();
            // 查找产品是否存在
            $isTrueGoods = $goodsModel->isTrueGoods($goodsId);
            if (!$isTrueGoods) {
                Log::write('此产品不存在、大兄die', 'info');
                return json(['code' => 0, '此产品不存在、大兄die', 'data' => []]);
            }

            $goodsItem = $goodsModel->getGoodsById($goodsId);
            $taoToken = $goodsItem['taoToken'];
            $url = $goodsItem['clickUrl'];
            $pic = $goodsItem['pic'];
            $title = $goodsItem['title'];
            unset($goodsItem);

            if (!$taoToken) {
                if ($url) {
                    vendor('taobao.TopClient');
                    vendor('taobao.ResultSet');
                    vendor('taobao.RequestCheckUtil');
                    vendor('taobao.TopLogger');
                    vendor('taobao.domain.GenPwdIsvParamDto');
                    vendor('taobao.request.TbkTpwdCreateRequest');
                    try {
                        $c = new \TopClient();
                        $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
                        $c->secretKey = config('web.WEB_TBSECREC');//淘宝客SECREC
                        $req = new \TbkTpwdCreateRequest;
                        $req->setUserId(config('web.WEB_TBUID'));//阿里妈妈UID
                        $req->setText($title);
                        $req->setUrl($url);
                        $req->setLogo($pic);
                        $req->setExt("{}");
                        $resp = $c->execute($req);
                        $taoToken = object_to_array($resp)['data']['model'];
                        $goodsModel->where('id', $goodsId)->update(['taoToken' => $taoToken]);
                    } catch (ErrorException $e) {
                        Log::write('生成淘口令失败' . $e->getMessage(), 'info');
                        return json(['code' => 0, 'msg' => '淘口令异常', 'data' => []]);
                    }
                } else {
                    Log::write('此产品没有推广链接、无法生成淘口令', 'info');
                    return json(['code' => 0, 'msg' => '此产品没有推广链接、无法生成淘口令', 'data' => []]);
                }
            }
            return json(['code' => 1, 'msg' => 'SUCCESS', 'data' => ['taoToken' => $taoToken]]);
        }
    }

    /**
     * 这个查商品详情（未解决）
     * @return \think\response\Json
     */
    public function goodsDesc()
    {
        $num_iid = input('goodsId', '');
        $goods_desc = '';
        $GoodsDb = Db::name('goods');
        $count = $GoodsDb->{'where'}(array('numIid' => $num_iid))->{'value'}('content');
        if ($count) {
            $goods_desc = $count;
        } else {
            $source = get_web_page('http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $num_iid . '%22%7D');
            $result_data = json_decode($source, true);
            $result_data = is_array($result_data) ? $result_data : '';
            $item = '';
            $num = $result_data['data']['images'];
            for ($i = 0; $i < count($num); $i++) {
                $item .= '<img  class="lazy" src="' . $num[$i] . '" style="width: 100%;">';
            }
            $goods_desc = $item;
        }
        if ($goods_desc) {
            $content['status'] = 200;
            $content['content'] = $goods_desc;
        }
        return json($content);
    }

    /**
     * 移动端上滑分页查询产品API（需要）
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function findGoodsList(Request $request)
    {
        if ($request->isPost()) {
            $title = input('ks');// 关键字
            $categoryId = input('cid');// 产品分类ID
            $sort = input('sort');//排序
            $price = input('price');//价格
            $volume = input('volume');//月销量

            $couponRate = '';
            switch ($price) {
                case 'nine'  :
                    $couponRate = 10;
                    break;
                case 'twenty':
                    $couponRate = 20;
                    break;
            }

            $goodsModel = new GoodsModel();
            $gList = [];
            $GoodsList = $goodsModel->findGoodsList($title, $categoryId, $sort, $couponRate, '', $volume);
            if ($GoodsList['goodsList']) {
                foreach ($GoodsList['goodsList'] as $key => $val) {
                    $tmp = $val;
                    $tmp['url'] = url('goods_item/' . $tmp['id']);
                    $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                    $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></div>';
                    $gList[] = $tmp;
                }
                $count = $GoodsList['goodsCount'];
                $pages = ceil($count / 40);
                return json(['code' => 1, 'msg' => 'SUCCESS', 'data' => ['data' => $gList, 'pages' => $pages]]);
            } else {
                Log::write('没有此产品数据', 'info');
                return json(['code' => 0, 'msg' => '没有此产品数据', 'data' => ['data' => [], 'pages' => 0]]);
            }
        }
    }

    // todo 手机版的浏览历史记录不知道后面需要不（先留着）
    public function historyList()
    {
        $history = cookie('person_dtl_history');
        if ($history) {
            $order = 'field(G.id,' . implode(',', array_reverse($history)) . ')';
            $GoodsDb = Db::name('goods');
            $show['G.show'] = 1;
            $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where('G.id', 'in', $history)->where($show)->order($order)->count();
            if ($count) {
                $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where('G.id', 'in', $history)->where($show)->order($order)->paginate(40);
                foreach ($GoodsList as $key => $val) {
                    $tmp = $val;
                    $tmp['url'] = url('dtl/' . $tmp['id']);
                    $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                    $tmp['newicon'] = newicon($tmp['startTime']);
                    $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                    $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                    $glist[] = $tmp;
                }
                $pages = ceil($count / 40);
            } else {
                $pages = 0;
            }
        } else {
            $pages = 0;
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }

    /**
     * todo 这个搜索废弃掉
     * @return \think\response\Json
     */
    public function suggest()
    {
        $data = input('ks', '');
        $source = post_web_page('http://suggest.taobao.com/sug?code=utf-8&q=' . $data);
        $result_data = json_decode($source, true);
        $result_data = $result_data['result'];
        $tags = '';
        $tags .= '<ul class="dropdown-menu">';
        if ($result_data) {
            foreach ($result_data as $k) {
                $ks = str_replace($data, "<b style=\"color:#ff464e;\">{$data}</b>", $k[0]);
                $tags .= '<li><a data-ks="' . $k[0] . '">' . $ks . '</a></li>';
            }
        }
        $tags .= '</ul>';
        if ($tags) {
            return json(array('code' => 1, 'msg' => '', 'data' => $tags));
        }
    }

    /**
     * todo 这个不知道后面需不需要
     * 超级搜索的商品生成淘口令
     * @return \think\response\Json
     */
    public function taobaoToken()
    {

        $clickUrl = urldecode(input('clickUrl', ''));//券二合一页面链接
        $title = urldecode(input('title', ''));
        $pic = urldecode(input('pic', ''));
        $url = urldecode(input('url', ''));//推广链接

        vendor('taobao.TopClient');
        vendor('taobao.ResultSet');
        vendor('taobao.RequestCheckUtil');
        vendor('taobao.TopLogger');
        vendor('taobao.domain.GenPwdIsvParamDto');
        vendor('taobao.request.TbkTpwdCreateRequest');
        vendor('taobao.request.WirelessShareTpwdCreateRequest');

        // 生成淘口令 - 此商品 有 券二合一页面链接则生成淘口令
        if ($clickUrl) {
            $clickUrl = 'https:' . $clickUrl;

            $c = new \TopClient();
            $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
            $c->secretKey = config('web.WEB_TBSECREC');//淘宝客SECREC
            $req = new \TbkTpwdCreateRequest;
            $req->setText($title);
            $req->setUrl($clickUrl);
            $req->setLogo($pic);
            $req->setUserId(config('web.WEB_TBUID'));//阿里妈妈UID
            $req->setExt("{}");
            $resp = $c->execute($req);
            $tao_token = object_to_array($resp)['data']['model'];
            return json($tao_token);
        }

        // 生成淘口令 - 此商品 没有 券二合一页面链接 则用 推广链接 生成淘口令

        if ($url) {
//            $url = str_replace(" ","+",$url);
            $c = new \TopClient;
            $c->appkey = config('web.WEB_TBKEY');
            $c->secretKey = config('web.WEB_TBSECREC');
            $req = new \WirelessShareTpwdCreateRequest;
            $tpwd_param = new \GenPwdIsvParamDto;
            $tpwd_param->logo = $pic;
            $tpwd_param->url = $url;
            $tpwd_param->text = $title;
            $tpwd_param->user_id = config('web.WEB_TBUID');
            $req->setTpwdParam(json_encode($tpwd_param));
            $resp = $c->execute($req);
            $tao_token = object_to_array($resp)['model'];
            return json($tao_token);
        }

        $tao_token = '没有淘口令';
        return json($tao_token);
    }

    // todo 这个废弃掉
    public function indexList2()
    {
        $data = input();
        $GoodsDb = Db::name('goods');
        $show['G.show'] = isset($data['G.show']) ? $data['G.show'] : 1;
        $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->count();
        $glist = [];
        if ($count) {
            $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->order('G.id desc')->paginate(40);
            foreach ($GoodsList as $key => $val) {
                $tmp = $val;
                $tmp['url'] = url('dtl/' . $tmp['id']);
                $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                $tmp['newicon'] = newicon($tmp['startTime']);
                $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                $glist[] = $tmp;
            }
            $pages = ceil($count / 40);
        } else {
            $pages = 0;
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }

    // todo 这个废弃掉
    public function catList()
    {
        $data = input();
        $id = $data['id'];
        $sort = $data['sort'];
        $order = '';
        switch ($sort) {
            case 'new':
                $order = 'G.startTime desc';
                break;

            case 'price':
                $order = 'G.couponPrice desc';
                break;

            case 'hot':
                $order = 'G.volume desc';
                break;

            case 'quan':
                $order = 'G.couponAmount desc';
                break;

            case 'rate':
                $order = 'G.couponRate asc';
        }
        $CategoryDb = Db::name('category');
        $Category = $CategoryDb->where("id = {$id}")->find();
        $glist = [];
        if ($Category) {
            $GoodsDb = Db::name('goods');
            $show['G.show'] = 1;
            $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where("G.cid={$id}")->where($show)->count();
            $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where("G.cid={$id}")->where($show)->order($order)->paginate(40);
            foreach ($GoodsList as $key => $val) {
                $tmp = $val;
                $tmp['url'] = url('dtl/' . $tmp['id']);
                $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                $tmp['newicon'] = newicon($tmp['startTime']);
                $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                $glist[] = $tmp;
            }
            $pages = ceil($count / 40);
        } else {
            $pages = 0;
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }

    // todo 这个废弃掉
    public function searchList()
    {
        $ks = input('ks');
        $glist = [];
        if (empty($ks)) {
            $pages = 0;
        } else {
            $GoodsDb = Db::name('goods');
            $show['G.show'] = 1;
            $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->order('G.id desc')->where($show)->where('title', 'like', '%' . $ks . '%')->count();
            if ($count) {
                $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->order('G.id desc')->where($show)->where('title', 'like', '%' . $ks . '%')->paginate(16, false, $config = ['query' => array('ks' => $ks)]);
                foreach ($GoodsList as $key => $val) {
                    $tmp = $val;
                    $tmp['url'] = url('dtl/' . $tmp['id']);
                    $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                    $tmp['newicon'] = newicon($tmp['startTime']);
                    $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                    $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                    $glist[] = $tmp;
                }
                $pages = ceil($count / 40);
            } else {
                $pages = 0;
            }
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }

    // todo 这个废弃掉
    public function jiuList()
    {
        $GoodsDb = Db::name('goods');
        $show['G.show'] = 1;
        $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->where('couponPrice', '<', 10)->count();
        $glist = [];
        if ($count) {
            $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->where('couponPrice', '<', 10)->order('G.id desc')->paginate(40);
            foreach ($GoodsList as $key => $val) {
                $tmp = $val;
                $tmp['url'] = url('dtl/' . $tmp['id']);
                $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                $tmp['newicon'] = newicon($tmp['startTime']);
                $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                $glist[] = $tmp;
            }
            $pages = ceil($count / 40);
        } else {
            $pages = 0;
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }

    // todo 这个废弃掉
    public function shijiuList()
    {
        $GoodsDb = Db::name('goods');
        $show['G.show'] = 1;
        $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->where('couponPrice', '<', 10)->count();
        $glist = [];
        if ($count) {
            $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->where('couponPrice', '<', 10)->order('G.id desc')->paginate(40);
            foreach ($GoodsList as $key => $val) {
                $tmp = $val;
                $tmp['url'] = url('dtl/' . $tmp['id']);
                $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                $tmp['newicon'] = newicon($tmp['startTime']);
                $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                $glist[] = $tmp;
            }
            $pages = ceil($count / 40);
        } else {
            $pages = 0;
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }

    // todo 这个废弃掉
    public function hotList()
    {
        $GoodsDb = Db::name('goods');
        $show['G.show'] = 1;
        $count = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->where('volume', '>', 100)->count();
        $glist = [];
        if ($count) {
            $GoodsList = $GoodsDb->alias('G')->join('category C', 'C.id=G.cid')->join('member M', 'M.userid=G.uid')->field('G.*,C.id as cid,M.userid,M.userhead,M.username,C.name')->where($show)->where('volume', '>', 100)->order('G.volume desc')->paginate(40);
            foreach ($GoodsList as $key => $val) {
                $tmp = $val;
                $tmp['url'] = url('dtl/' . $tmp['id']);
                $tmp['jumpurl'] = url('jump/index') . '?id=' . $tmp['id'];
                $tmp['newicon'] = newicon($tmp['startTime']);
                $tmp['icon'] = !($tmp['userType']) ? 't-icon' : 'm-icon';
                $tmp['couponAmount'] = !($tmp['couponAmount']) ? '' : '<div class="quan"><a href="' . $tmp['jumpurl'] . '" rel="nofollow"><span class="quan-info">优惠券<br><em>' . $val['couponAmount'] . '元</em></span></a></div>';
                $glist[] = $tmp;
            }
            $pages = ceil($count / 40);
        } else {
            $pages = 0;
        }
        return json(['data' => $glist, 'pages' => $pages]);
    }
}